﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Tools.Service.File;
using Tools.Utils;
using Tools.Web.Models;

namespace Tools.Web.Controllers
{
    public class VideoController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 视频添加水印
        /// </summary>
        /// <returns></returns>
        public IActionResult VideoAddWatermark()
        {
            return View();
        }

        /// <summary>
        /// 视频添加水印
        /// </summary>
        /// <param name="oldPath">视频路径</param>
        /// <param name="watermarkPath">水印图片路径</param>
        /// <param name="waterMarkName">水印文字</param>
        /// <param name="type">类型（img-图片,text-文字）</param>
        /// <param name="layout">布局（1-左上方，2顶部中间，3-右上方，4-左边，5-中间，6-右边，7-左下方，8-底部中间，9-右下方）</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateVideoAddWatermark(string oldPath, string watermarkPath, string waterMarkName, string type, string layout)
        {
            ResultMessage resultMessage = new ResultMessage();

            if (string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";
            oldPath = $"{FileHelper.UploadFilePath}\\{oldPath}";

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string suffix = System.IO.Path.GetExtension(oldPath);
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}{suffix}";
                showUrl = $"/files/video/{newFileName}{suffix}";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().AddWatermark(oldPath, saveFilePath, $"{FileHelper.UploadFilePath}\\{watermarkPath}", waterMarkName, type, layout);

                return Json(resultMessage.Success(new { msg = $"水印添加成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 视频合并
        /// </summary>
        /// <returns></returns>
        public IActionResult VideoMerge()
        {
            return View();
        }

        /// <summary>
        /// 视频合并
        /// </summary>
        /// <param name="pathList">视频路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateVideoMerge(List<string> pathList)
        {
            ResultMessage resultMessage = new ResultMessage();


            if (pathList == null || pathList.Count() < 2)
            {
                return Json(resultMessage.Failure("请上传至少两个以上文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";

            pathList = pathList.Distinct().Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => $"{FileHelper.UploadFilePath}\\{t}").ToList();

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}.mp4";
                showUrl = $"/files/video/{newFileName}.mp4";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().VideoCombine(pathList, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"视频合并成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 音频合并
        /// </summary>
        /// <returns></returns>
        public IActionResult AudioMerge()
        {
            return View();
        }

        /// <summary>
        /// 音频合并
        /// </summary>
        /// <param name="pathList">音频路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateAudioMerge(List<string> pathList)
        {
            ResultMessage resultMessage = new ResultMessage();


            if (pathList == null || pathList.Count() < 2)
            {
                return Json(resultMessage.Failure("请上传至少两个以上文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";

            pathList = pathList.Distinct().Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => $"{FileHelper.UploadFilePath}\\{t}").ToList();

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\audio\\{newFileName}.mp3";
                showUrl = $"/files/audio/{newFileName}.mp3";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\audio";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().AudioMerge(pathList, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"音频合并成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 视频转音频
        /// </summary>
        /// <returns></returns>
        public IActionResult VideoAudio()
        {
            return View();
        }

        /// <summary>
        /// 视频转音频
        /// </summary>
        /// <param name="oldPath">视频路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetVideoAudio(string oldPath)
        {
            ResultMessage resultMessage = new ResultMessage();


            if (string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";

            oldPath = $"{FileHelper.UploadFilePath}\\{oldPath}";

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\audio\\{newFileName}.mp3";
                showUrl = $"/files/audio/{newFileName}.mp3";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\audio";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().VideGetAudio(oldPath, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"转换成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 删除视频中的音频
        /// </summary>
        /// <returns></returns>
        public IActionResult VideoRemoveAudio()
        {
            return View();
        }

        /// <summary>
        /// 删除视频中的音频
        /// </summary>
        /// <param name="oldPath">视频路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateVideoRemoveAudio(string oldPath)
        {
            ResultMessage resultMessage = new ResultMessage();

            if (string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";

            oldPath = $"{FileHelper.UploadFilePath}\\{oldPath}";

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string suffix = System.IO.Path.GetExtension(oldPath);
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}{suffix}";
                showUrl = $"/files/video/{newFileName}{suffix}";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().VideGetAudio(oldPath, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"删除成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }


        /// <summary>
        /// 音频视频合并
        /// </summary>
        /// <returns></returns>
        public IActionResult AudioVideoMerge()
        {
            return View();
        }

        /// <summary>
        /// 音频视频合并
        /// </summary>
        /// <param name="videoPath">视频路径</param>
        /// <param name="audioPath">音频路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateAudioVideoMerge(string videoPath, string audioPath)
        {
            ResultMessage resultMessage = new ResultMessage();

            if (string.IsNullOrWhiteSpace(videoPath) || string.IsNullOrWhiteSpace(audioPath))
            {
                return Json(resultMessage.Failure("请上传视频与音频，如都已上传，请刷新后重试"));
            }

            var showUrl = "";

            videoPath = $"{FileHelper.UploadFilePath}\\{videoPath}";
            audioPath = $"{FileHelper.UploadFilePath}\\{audioPath}";

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string suffix = System.IO.Path.GetExtension(videoPath);
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}{suffix}";
                showUrl = $"/files/video/{newFileName}{suffix}";
                var videoDirectoryPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoDirectoryPath))
                {
                    Directory.CreateDirectory(videoDirectoryPath);
                }

                new VideoService().AudioAndVideoMerge(videoPath, audioPath, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"合并成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 图片转成视频
        /// </summary>
        /// <returns></returns>
        public IActionResult ImageToVideo()
        {
            return View();
        }

        /// <summary>
        /// 图片合并为视频
        /// </summary>
        /// <param name="pathList">图片路径</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateImageToVideo(List<string> pathList, string audio)
        {
            ResultMessage resultMessage = new ResultMessage();

            if (pathList == null || pathList.Count() < 1)
            {
                return Json(resultMessage.Failure("请上传文件，如已上传，请刷新后重试"));
            }

            var showUrl = "";
            string newFileGuid = Guid.NewGuid().ToString().Replace("-", "");
            var directoryPath = new DirectoryInfo($"{ FileHelper.UploadFilePath}\\{pathList[0]}").Parent.FullName;
            audio = !string.IsNullOrWhiteSpace(audio) ? $"{ FileHelper.UploadFilePath}\\{audio}" : "";

            for (int i = 0; i < pathList.Count(); i++)
            {
                var path = pathList[i];
                var newPath = $"{directoryPath}\\{newFileGuid}_{i}.jpeg";
                System.IO.File.Copy($"{ FileHelper.UploadFilePath}\\{path}", newPath);
                pathList[i] = newPath;
            }
            //pathList = pathList.Distinct().Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => $"{FileHelper.UploadFilePath}\\{t}").ToList();

            try
            {
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}.mp4";
                showUrl = $"/files/video/{newFileName}.mp4";
                var videoPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoPath))
                {
                    Directory.CreateDirectory(videoPath);
                }

                new VideoService().ImagesToVideo(pathList.Count(), directoryPath, newFileGuid, saveFilePath, audio);

                return Json(resultMessage.Success(new { msg = $"合并成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }

        /// <summary>
        /// 视频添加片头片尾图片
        /// </summary>
        /// <returns></returns>
        public IActionResult VideoAddImage()
        {
            return View();
        }

        /// <summary>
        /// 视频添加片头片尾图片
        /// </summary>
        /// <param name="videoPath">视频路径</param>
        /// <param name="imagePath">图片路径</param>
        /// <param name="type">片头或片尾（1-片头；2-片尾）</param>
        /// <param name="time">停留时长</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateVideoAddImage(string videoPath, string imagePath, string type, int time = 1)
        {
            ResultMessage resultMessage = new ResultMessage();

            if (string.IsNullOrWhiteSpace(videoPath) || string.IsNullOrWhiteSpace(imagePath))
            {
                return Json(resultMessage.Failure("请上传视频与图片，如都已上传，请刷新后重试"));
            }

            try
            {
                var showUrl = "";
                var videoPathList = new List<string>();
                videoPath = $"{FileHelper.UploadFilePath}\\{videoPath}";
                imagePath = $"{FileHelper.UploadFilePath}\\{imagePath}";

                //图片复制一个并重命名
                string newFileGuid = Guid.NewGuid().ToString().Replace("-", "");
                var directoryPath = new DirectoryInfo(imagePath).Parent.FullName;
                var newPath = $"{directoryPath}\\{newFileGuid}_{0}.jpeg";
                System.IO.File.Copy(imagePath, newPath);

                string imageToVideo = $"{FileHelper.UploadFilePath}\\files\\video\\{Guid.NewGuid().ToString().Replace("-", "")}.mp4";
                string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                string suffix = System.IO.Path.GetExtension(videoPath);
                string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\video\\{newFileName}{suffix}";
                showUrl = $"/files/video/{newFileName}{suffix}";
                var videoDirectoryPath = $"{FileHelper.UploadFilePath}\\files\\video";  //存放处理之后视频的路径

                if (!Directory.Exists(videoDirectoryPath))
                {
                    Directory.CreateDirectory(videoDirectoryPath);
                }

                //先将图片转成视频
                new VideoService().ImagesToVideo(1, directoryPath, newFileGuid, imageToVideo, time: time);

                if (type == "2")
                {
                    videoPathList.Add(videoPath);
                    videoPathList.Add(imageToVideo);
                }
                else
                {
                    videoPathList.Add(imageToVideo);
                    videoPathList.Add(videoPath);
                }

                new VideoService().VideoCombine(videoPathList, saveFilePath);

                return Json(resultMessage.Success(new { msg = $"添加成功。", url = showUrl }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }


    }
}
